<template>
	<view class="content">
		<view class="main" :style="{'margin-top':`${menuBarHeight}px`}">
			<view class="cover">
				<image src="/static/logo.jpg" mode=""></image>
			</view>
			<view class="login-btn">
				<button class="mobile-btn" open-type="getPhoneNumber" @getphonenumber="getUserPhoneAuth"
					v-if="!isModal">手机号一键授权</button>
			</view>
			<u-modal :show="isModal" :closeOnClickOverlay="true" title="潇湘键盘" content="获取您的微信昵称及头像" width="500rpx"
				@close="isModal = !isModal">
				<view class="slot-content" slot="confirmButton">
					<button @click="getUserInfoAuth">一键登录</button>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	export default {
		name: "login",
		data() {
			return {
				isModal: false, // 用户信息授权弹框
				mobile: null // 用户电话号码
			}
		},
		onLoad() {
			this.login()
		},
		methods: {
			// 获取用户手机号授权
			getUserPhoneAuth(e) {
				// 同意授权
				if (e.detail.code) {
					this.$http.getUserPhone({
						code: e.detail.code
					}).then(res => {
						this.mobile = res
						this.isModal = true
					}).catch(err => {
						uni.showToast({
							title: "手机号获取失败 请重试",
							icon: 'none'
						})
					})
				} else { // 拒绝授权
					uni.$u.toast("手机号授权失败")
				}

			},
			// 获取用户信息授权
			getUserInfoAuth() {
				uni.getUserProfile({
					desc: "获取用户信息",
					success: (res) => {
						let {
							session_key
						} = uni.getStorageSync("session")
						let {
							signature,
							iv,
							encryptedData
						} = res
						this.$http.userLogin({
							session_key,
							signature,
							iv,
							encryptedData,
							mobile: this.mobile,
							event: "login"
						}).then(info => {
							let {
								token
							} = info
							// 储存用户token
							this.$store.commit("saveToken", token)
							uni.setStorageSync("token", token)

							// 登录成功 获取用户信息
							this.getUserInfo()
							uni.navigateBack()
						})
					},
					fail: () => {
						uni.$u.toast("登录失败")
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.content {
		width: 100%;

		.main {
			.cover {
				display: flex;
				justify-content: center;

				&>image {
					width: 80VW;
					height: 80vw;
				}
			}

			.login-btn {
				width: 100%;
				margin-top: 70rpx;
				display: flex;
				justify-content: center;

				.mobile-btn {
					width: 50%;
					font-size: 28rpx;
					font-weight: bold;
					color: #fff;
					background-color: #277dff;
				}
			}

			.slot-content {
				display: flex;
				justify-content: center;

				&>button {
					width: 70%;
					font-size: 26rpx;
					font-weight: bold;
					color: #fff;
					background-color: #277dff;
				}

			}
		}
	}
</style>
